﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Text;
using System.Data.OleDb;

/// <summary>
/// Summary description for ConnectDB
/// </summary>
public class ConnectBD
{
    public OleDbDataAdapter da;
    OleDbConnection conn = null;
    String Host = "";
    String Username = "";
    String Password = "";
    String Database = "";
    //String này dùng để phi ra lỗi khi truy cập CSDL
    public String err = "";
    public ConnectBD(String Host, String Username, String Password, String Database)
    {
        this.Host = Host;
        this.Username = Username;
        this.Password = Password;
        this.Database = Database;
    }

    public OleDbConnection getConnect()
    {
        if (this.conn == null)
        {
            try
            {
                this.conn = new OleDbConnection("Provider=SQLNCLI;Server=" + this.Host + ";Database=" + this.Database + ";Uid=" + this.Username + ";Pwd=" + this.Password + ";");
            }
            catch (Exception e)
            {
                this.err = "Connect Fail! " + e.Message;
            }
        }
        return this.conn;
    }
    //Trả về số record được cập nhật, thêm, xóa ...
    public int executeUpdate(String query)
    {
        int res = 0;
        OleDbCommand Cmd = new OleDbCommand(query, getConnect());
        
        try
        {
            Cmd.Connection.Open();
            res = Cmd.ExecuteNonQuery();
        }
        catch (Exception e)
        {
            this.err = "Lỗi khi executeUpdate" + e.Message;
        }
        finally
        {
            Cmd.Connection.Close();
            Close();
        }
        return res;
    }

    //Thực hiện câu lệnh truy vấn và trả về 1 dataset
    public DataSet executeQuery(String query)
    {
        DataSet DS = new DataSet();
        try
        {
            this.da = new OleDbDataAdapter(query, getConnect());
            da.Fill(DS, "data");
        }
        catch (Exception e)
        {
            this.err = "Lỗi khi lấy dữ liệu về: " + e.Message;
        }
        finally
        {
            Close();
        }
        return DS;
    }
    //Đóng kết nối Database
    public void Close()
    {
        if (this.conn != null && this.conn.State.ToString() == "Open")
        {
            conn.Close();
        }
    }
}
